package com.example.demo.conf;
import com.example.demo.util.JwtUtil;

import javax.servlet.annotation.WebFilter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


@WebFilter(filterName = "jwtFilter", urlPatterns = "/*")  // 在所有请求之前执行过滤器
public class JwtFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化操作
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        // 获取请求头中的 token
        String token = httpRequest.getHeader("Authorization");

        if (token != null && !token.isEmpty()) {
            token = token.replace("Bearer ", "");  // 移除 "Bearer " 前缀

            // 从 token 中获取用户名并验证
            String username = JwtUtil.getUsernameFromToken(token);
            if (username != null && JwtUtil.validateToken(token, username)) {
                // 通过验证，则允许请求继续
                httpRequest.setAttribute("username", username);
            } else {
                // 如果 Token 无效，可以返回 401 未授权错误
                response.getWriter().write("Unauthorized");
                return;
            }
        } else {
            // 如果没有提供 Token，可以返回 401 未授权错误
            response.getWriter().write("Unauthorized");
            return;
        }

        chain.doFilter(request, response);  // 放行请求
    }

    @Override
    public void destroy() {
        // 释放资源
    }
}